# @Version        : 1.0
# @Update Time    : 2024/6/16 21:10
# @File           : dict_controller.py
# @IDE            : PyCharm
# @Desc           : 数据字典接口
from typing import List, Dict

from fastapi import APIRouter, Depends, Body
from fastapi_utils.cbv import cbv
from sqlalchemy import and_
from sqlalchemy.ext.asyncio import AsyncSession

from authx.dependencies.auth import RequireLogin
from authx.dependencies.permission import PermissionChecker
from src import schemas
from src.core.base_controller import BaseController
from src.core.dependencies import IdList
from src.core.response.response_schema import (
    ResponseGenericSchema,
    ResponseSchema,
    PageResponse,
)
from src.db.db_database import alchemy
from src.models import SysDictData
from src.schemas.dict_schema import DictOptions, DictTypeParams
from src.services.dict_service import DictTypeService, DictDataService

router = APIRouter()


# ===============================
# 用户管理
# ===============================
@cbv(router)
class DictController(BaseController):
    db: AsyncSession = Depends(alchemy.provide_session())

    # 查询字典类型列表
    @router.get(
        "/type/list",
        summary="字典类型列表",
        response_model=PageResponse[schemas.DictTypeSchemaOut],
        dependencies=[Depends(RequireLogin())],
    )
    async def get_dict_type_list(self, param: DictTypeParams = Depends()):
        where = await param.get_where_and_limit_offset(SysDictData)
        res, count = await DictTypeService(self.db).list_and_count(
            *where, auto_expunge=True
        )
        return self.paginated_response(
            data=res,
            total=count,
            current=param.page,
            size=param.limit,
        )

    # 创建
    @router.post(
        "/type/add",
        summary="创建字典类型",
        description="创建字典类型",
        dependencies=[Depends(PermissionChecker("system:dict:add"))],
        response_model=ResponseSchema,
    )
    async def add_dict_type(
        self,
        model: schemas.DictTypeSchema,
    ):
        await DictTypeService(self.db).create(model, auto_commit=True)
        return self.success(message="创建成功")

    # 更新
    @router.put(
        "/type/update",
        summary="更新字典类型",
        description="更新字典类型",
        dependencies=[Depends(PermissionChecker("system:dict:update"))],
        response_model=ResponseSchema,
    )
    async def update_dict_type(
        self,
        model: schemas.DictTypeSchemaOut,
    ):
        await DictTypeService(self.db).update(data=model, auto_commit=True)
        return self.success(message="更新成功")

    # 获取字典options
    @router.post(
        "/options",
        summary="获取字典options",
        description="获取字典options",
        dependencies=[Depends(RequireLogin())],
        response_model=ResponseGenericSchema[Dict[str, list[DictOptions]]],
    )
    async def get_dict_options(self, keys: List[str] = Body(...)):
        data = await DictTypeService(self.db).get_options(keys)
        return self.success(data=data)

    @router.delete(
        "/type/delete",
        summary="删除字典类型",
        description="删除字典类型",
        dependencies=[Depends(PermissionChecker("system:dict:delete"))],
        response_model=ResponseSchema,
    )
    async def delete_dict_type(
        self,
        ids: IdList = Depends(),
    ):
        await DictTypeService(self.db).delete_many(ids.ids, auto_commit=True)
        return self.success(message="删除成功")

    @router.get(
        "/data/{dict_type_id}/list",
        summary="字典数据列表",
        response_model=ResponseGenericSchema[list[schemas.DictDataSchemaOut]],
        dependencies=[Depends(RequireLogin())],
    )
    async def get_dict_data_list(self, dict_type_id: int):
        """
        # 根据字典类型id查询字典数据
        :param dict_type_id:
        :return:
        """
        res = await DictDataService(self.db).list(
            and_(SysDictData.dict_type_id == dict_type_id)
        )
        return self.success(data=res)

    # 创建字典数据
    @router.post(
        "/data/add",
        summary="创建字典数据",
        description="创建字典数据",
        dependencies=[Depends(PermissionChecker("system:dict_data:add"))],
        response_model=ResponseSchema,
    )
    async def add_dict_data(
        self,
        model: schemas.DictDataSchema,
    ):
        await DictDataService(self.db).create(model, auto_commit=True)
        return self.success(message="创建成功")

    @router.put(
        "/data/update",
        summary="更新字典数据",
        description="更新字典数据",
        dependencies=[Depends(PermissionChecker("system:dict_data:update"))],
        response_model=ResponseSchema,
    )
    async def update_dict_data(
        self,
        model: schemas.DictDataSchemaOut,
    ):
        await DictDataService(self.db).update(
            item_id=model.id, data=model, auto_commit=True
        )
        return self.success(message="更新成功")

    # 删除字典数据
    @router.delete(
        "/data/delete/{data_id}",
        summary="删除字典数据",
        description="删除字典数据",
        dependencies=[Depends(PermissionChecker("system:dict_data:delete"))],
        response_model=ResponseSchema,
    )
    async def delete_dict_data(
        self,
        data_id: int,
    ):
        await DictDataService(self.db).delete_many([data_id], auto_commit=True)
        return self.success(message="删除成功")
